<template>
  <el-dialog :visible.sync="dialogVisibleInner" :title="titleText" top="5vh" width="57%" v-el-drag-dialog
    :close-on-press-escape="false" :close-on-click-modal="false" @close="handleClose" class="custom-dialog"
    @open="scrollToTop" :fullscreen="isFullscreen">
    <!-- 顶部分割线 -->
    <el-divider content-position="left">基本信息</el-divider>
    <el-form class="rule-container" :model="dialogForm" label-width="100px">
      <div class="rule-content">
        <el-form-item label="标题:">
          <el-input v-model="dialogForm.Title" :readonly="Action === 4" />
        </el-form-item>
        <el-form-item label="分类:">
          <el-cascader ref="cascaderAddr" style="width:100%" v-model="dialogForm.ClassID" :options="classList"
            :props="{ value: 'value', label: 'label', children: 'children', emitPath: false, checkStrictly: true, expandTrigger: 'hover' }"
            @visible-change="elCascaderOnlick" @expand-change="elCascaderOnlick" placeholder="请选择分类" class="full-width"
            :disabled="Action === 4" :popper-class="this.color === 'night' ? 'nightClass' : ''" />
        </el-form-item>
        <el-form-item label="内容:">
          <div v-if="Action !== 4">
            <wang-editor :value="dialogForm.ContentLink" v-model="dialogForm.ContentLink"></wang-editor>
          </div>
          <div class="chat-message-text" v-html="markdownText" v-if="Action === 4"></div>
        </el-form-item>
      </div>
    </el-form>
    <!-- 分割线与dialog-footer的间距 -->
    <el-divider class="lineToFooter"></el-divider>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" v-if="Action !== 4">
          确认
        </el-button>
        <el-button type="info" @click="handleClose">{{ Action === 4 ? '关闭' : '取消' }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
window.copy = function (elementId) {
  var element = document.getElementById(elementId);
  var tempInput = document.createElement("textarea");
  tempInput.value = element.textContent || element.innerText;
  document.body.appendChild(tempInput);
  tempInput.select();
  document.execCommand('copy');
  document.body.removeChild(tempInput);
  Message.success('复制成功');
}

// 初始化 MarkdownIt
const md = new MarkdownIt({
  html: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && Hljs.getLanguage(lang)) {
      try {
        let idname = `name${getuuid()}`;
        return `<pre class="hljs"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><el-button class="code-block-header__copy" onClick='copy("${idname}")'>复制代码</el-button></div><code id='${idname}'>` +
          Hljs.highlight(lang, str, true).value +
          '</code></pre>';
      } catch (__) { }
    }
    return '';
  }
});

// 自定义图片渲染规则
md.renderer.rules.image = (tokens, idx, options, env, self) => {
  const token = tokens[idx];
  const src = token.attrGet('src');
  const alt = token.content;
  return `<img src="${src}" alt="${alt}" style="height: 600px;" />`;
};

import { Message } from 'element-ui';
import 'highlight.js/styles/monokai-sublime.css';
import Hljs from "highlight.js";
import MarkdownIt from 'markdown-it/dist/markdown-it.js';
import { getuuid } from '@/utils/index.js';
import WangEditor from '@/components/WangEditor';
import elDragDialog from "@/directive/el-drag-dialog";

export default {
  name: 'KnowledgeBaseDialog',
  components: {
    WangEditor
  },
  directives: { elDragDialog },
  props: {
    dialogVisible: Boolean,
    classList: Array,
    Action: Number,
    dialogForm: Object
  },
  data() {
    return {
      dialogVisibleInner: false,
      md: md,
      markdownText: '',
      color: '',
      isFullscreen: false
    };
  },
  mounted() {
    this.color = localStorage.getItem('isNightMode') || 'night';
  },
  computed: {
    titleText() {
      if (this.Action === 1) return '添加企业智库';
      if (this.Action === 2) return '修改企业智库';
      return '预览企业智库';
    }
  },
  watch: {
    dialogVisible(newValue) {
      this.changeHeight();
      this.dialogVisibleInner = newValue;
      if (newValue) {
        this.markdownText = this.md.render(this.dialogForm.ContentLink || '');

        // 对话框打开时，添加最大化/最小化按钮（仅当 Action === 4）
        this.addMaximizeButton();
      } else {
        // 对话框关闭时，移除按钮
        this.removeMaximizeButton();
        this.isFullscreen = false; // 重置全屏状态
      }
    }
  },
  beforeDestroy() {
    window.copy = undefined;
    // 组件销毁时移除按钮
    this.removeMaximizeButton();
  },
  methods: {
    addMaximizeButton() {
      // 仅当 Action === 4 时添加按钮
      if (this.Action !== 4) return;

      this.$nextTick(() => {
        const header = this.$el.querySelector('.el-dialog__header');
        if (header) {
          // 避免重复添加
          this.removeMaximizeButton();

          const button = document.createElement('button');
          button.className = 'el-button el-button--text custom-maximize-button';
          button.innerHTML = `<i class="${this.isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'
            }"></i>`;
          button.addEventListener('click', this.toggleMaximize);
          const closeButton = header.querySelector('.el-dialog__headerbtn');
          if (closeButton) {
            header.insertBefore(button, closeButton);
          } else {
            header.appendChild(button);
          }
        }
      });
    },
    removeMaximizeButton() {
      const button = this.$el.querySelector('.custom-maximize-button');
      if (button) {
        button.removeEventListener('click', this.toggleMaximize);
        button.remove();
      }
    },
    scrollToTop() {
      this.$nextTick(() => {
        this.$el.querySelector('.el-dialog__body').scrollTop = 0;
      });
    },
    handleClose() {
      this.isFullscreen = false;
      this.dialogVisibleInner = false;
      this.$emit('closeDialog');
    },
    handleSubmit() {
      this.$emit('submitDialog', this.dialogForm, this.Action);
      this.dialogVisibleInner = false;
      this.$emit('closeDialog');
    },
    toggleMaximize() {
      this.isFullscreen = !this.isFullscreen;
      const button = this.$el.querySelector('.custom-maximize-button');
      if (button) {
        button.innerHTML = `<i class="${this.isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'
          }"></i>`;
      }
      this.changeHeight();
    },
    elCascaderOnlick() {
      let that = this;
      setTimeout(function () {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function () {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    },
    changeHeight() {
      const dialog = this.$el.querySelector(".el-dialog")
      const dialogBody = this.$el.querySelector(".el-dialog__body");
      const ruleContainer = this.$el.querySelector(".rule-container")
      const chatMess = this.$el.querySelector(".chat-message-text")
      if (dialogBody && ruleContainer && chatMess) {
        if (this.isFullscreen) {
          dialog.style.left = '0';
          dialog.style.top = '0';
          dialogBody.style.height = 'calc(100% - 106px)';
          dialogBody.style.maxHeight = '100vh';
          ruleContainer.style.height = 'calc(100% - 32px)';
          chatMess.style.height = '60vh'
        } else {
          // 恢复默认高度（移除自定义高度，让 CSS 样式生效）
          dialogBody.style.height = '';
          dialogBody.style.maxHeight = '';
          ruleContainer.style.height = '';
          chatMess.style.height = '';
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.chat-message-text {
  width: 100%;
  overflow-y: auto;
  align-self: flex-start;
  border-radius: 5px;
  padding: 0 10px;
  background-color: #f4f6f8;
  word-wrap: break-word;
}

.night {
  .chat-message-text {
    background-color: #3e4252;
  }
}

.hljs {
  padding: 10px;
  border-radius: 0 0 4px 4px;
}

::v-deep .el-dialog__body {
  max-height: 75vh;
  overflow-y: auto;
}

/* 调整 el-dialog 标题区域 */
.custom-dialog {
  ::v-deep .el-dialog__header {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    height: 40px;
  }

  ::v-deep .el-dialog__title {
    flex: 1;
    line-height: 20px;
  }

  ::v-deep .custom-maximize-button {
    margin-right: 15px;
    padding: 0;
    font-size: 16px;
    color: #606266;
    line-height: 20px;
    display: inline-flex;
    align-items: center;

    .el-icon-minus,
    .el-icon-full-screen {
      font-size: 16px;
    }
  }

  ::v-deep .el-dialog__headerbtn {
    position: static;
    line-height: 20px;
    display: inline-flex;
    align-items: center;

    .el-dialog__close {
      font-size: 16px;
    }
  }
}

::v-deep .el-icon-full-screen:before,
::v-deep .el-icon-minus:before {
  color: #fff;
}
</style>

<!-- 全局样式（保持不变） -->
<style lang="scss">
code {
  font-size: 14px;
  font-family: '微软雅黑' !important;
}

.code-block-header {
  width: 100%;
  background: #000 !important;
  display: flex;
  justify-content: space-between;
  color: #dddddd;
}

.code-block-header__lang,
.code-block-header__copy {
  padding: 5px;
  cursor: pointer;
}

.night {
  .w-e-toolbar {
    background-color: #2a2d3c !important;
    border: 1px solid #414556 !important;
  }

  .w-e-text-container {
    border: 1px solid #414556 !important;
  }
}
</style>